package com.tiemei.demo.beanutils;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.beanutils.PropertyUtils;

public class ReadBeanProperty {
	public static void main(String[] args) {
		Track track = new Track();
		track.setTitle("Till There Was You");

		try {
			/*
			 * read type
			 */
			Class type = PropertyUtils.getPropertyType(track, "title");
			System.out.println("type = " + type.getName());

			/*
			 * read value
			 */
			String title = (String) PropertyUtils.getSimpleProperty(track,
					"title");
			System.out.println("Title = " + title);

			/*
			 * read 一个map类型field中一个值
			 */
			Recording re = new Recording();
			re.getMapTracks().put("T1", track);
			Track track_ = (Track) PropertyUtils.getMappedProperty(re, "mapTracks(T1)");
			System.out.println("track.getTitle() = " + track_.getTitle());
			
			/*
			 * read nested value 
			 * array/list
			 */
			Artist artist = new Artist();
	        artist.setId(1);
	        artist.setName("Beatles");
	        track.setArtist(artist);
	        
	        String artistName = (String) PropertyUtils.getNestedProperty(track, "artist.name");
            System.out.println("Artist Name = " + artistName);

            
            /*
             * read indexed value
             */
            re.getTracks().add(track);
            System.out.println(PropertyUtils.getIndexedProperty(re, "tracks[0]"));
            
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}
}
